package day27;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

//通过Socket结合多线程 读写数据
public class Server2 {
    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(9999);
        while (true) {
            Socket client=server.accept();
            System.out.println(client.getInetAddress()+"连接成功");
            //因为每个客户端去连接服务端 client都是不同的，读写的数据也不同
            //所以我就需要线程，每个客户端通过一个线程，来负责当前客户端的读写
            new Server2Thread(client).start();
        }
    }
}
//每个线程负责每个客户端的数据读写
class Server2Thread extends Thread{
    Socket client; //客户端对象
    public Server2Thread(Socket client){
        this.client=client;
    }
    public void run() {
        //负责读取当前客户端给我写入的数据即可
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (true){
                String msg=br.readLine();
                System.out.println(client.getInetAddress()+":"+msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}